package org.walklink.core.plugins.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.walklink.common.constant.NetWorkDefaultConstant;
import org.walklink.common.util.ObjectAndByteUtil;
import org.walklink.core.client.ClientInitializer;
import org.walklink.core.config.Config;
import org.walklink.core.config.ConfigHelper;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * UDP客户端
 *
 * @author lidishan
 * @date 2021/04/23
 */
public class UdpClientPlugin implements IClientPlugin {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientInitializer.class);

    private static SocketAddress address;
    private static DatagramSocket socket;



    public UdpClientPlugin() {
        try {
            String host = ConfigHelper.getString(Config.UDP_CLIENT_HOST, NetWorkDefaultConstant.LOCAL_HOST);
            Integer port = ConfigHelper.getInt(Config.UDP_CLIENT_PORT, NetWorkDefaultConstant.PORT);
            address = new InetSocketAddress(host, port);
            socket = new DatagramSocket();
        } catch (Exception e) {
            LOGGER.error("[UDPHelper_error] UdpClientPlugin", e);
        }
    }

    @Override
    public void send(byte[] bytes) {
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address);
        if (!socket.isClosed()) {
            try {
                socket.send(packet);
            } catch (IOException e) {
                LOGGER.error("[UDPHelper_error] send bytes", e);
            }
        }
    }

    @Override
    public void send(Object obj) {
        // 将Object转为byte数组
        byte[] bytes = ObjectAndByteUtil.toByteArray(obj);
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address);
        if (!socket.isClosed()) {
            try {
                socket.send(packet);
            } catch (IOException e) {
                LOGGER.error("[UDPHelper_error] send obj", e);
            }
        }
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
